﻿using MetaProperties.Core.EventFilters;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using MetaProperties.Core;
using System;

namespace MetaProperties.Core.EventFilters.Tests
{
    using System.Threading;

    using Framework;

    using SynchronizationContexts;


    /// <summary>
    ///This is a test class for DispatchingEventFilterTest and is intended
    ///to contain all DispatchingEventFilterTest Unit Tests
    ///</summary>
    [TestClass()]
    public class DispatchingEventFilterTest
    {


        private TestContext testContextInstance;

        /// <summary>
        ///Gets or sets the test context which provides
        ///information about and functionality for the current test run.
        ///</summary>
        public TestContext TestContext
        {
            get
            {
                return testContextInstance;
            }
            set
            {
                testContextInstance = value;
            }
        }

        #region Additional test attributes
        // 
        //You can use the following additional attributes as you write your tests:
        //
        //Use ClassInitialize to run code before running the first test in the class
        //[ClassInitialize()]
        //public static void MyClassInitialize(TestContext testContext)
        //{
        //}
        //
        //Use ClassCleanup to run code after all tests in a class have run
        //[ClassCleanup()]
        //public static void MyClassCleanup()
        //{
        //}
        //
        //Use TestInitialize to run code before running each test
        //[TestInitialize()]
        //public void MyTestInitialize()
        //{
        //}
        //
        //Use TestCleanup to run code after each test has run
        //[TestCleanup()]
        //public void MyTestCleanup()
        //{
        //}
        //
        #endregion


        /////// <summary>
        ///////A test for Resume
        ///////</summary>
        ////[TestMethod()]
        ////[DeploymentItem("MetaProperties.Core.EventFilters.dll")]
        ////public void ResumeTest()
        ////{
        ////    DispatchingEventFilter_Accessor target = new DispatchingEventFilter_Accessor(); // TODO: Initialize to an appropriate value
        ////    object sender = null; // TODO: Initialize to an appropriate value
        ////    EventArgs args = null; // TODO: Initialize to an appropriate value
        ////    IFilterPipeline pipeline = null; // TODO: Initialize to an appropriate value
        ////    target.Resume(sender, args, pipeline);
        ////    Assert.Inconclusive("A method that does not return a value cannot be verified.");
        ////}

        /////// <summary>
        ///////A test for DispatchingEventFilter Constructor
        ///////</summary>
        ////[TestMethod()]
        ////public void DispatchingEventFilterConstructorTest1()
        ////{
        ////    DispatchingEventFilter target = new DispatchingEventFilter();
        ////    Assert.Inconclusive("TODO: Implement code to verify target");
        ////}

        /////// <summary>
        ///////A test for DispatchingEventFilter Constructor
        ///////</summary>
        ////[TestMethod()]
        ////public void DispatchingEventFilterConstructorTest()
        ////{
        ////    ISynchronizationContextContainer context = null; // TODO: Initialize to an appropriate value
        ////    DispatchingEventFilter target = new DispatchingEventFilter(context);
        ////    Assert.Inconclusive("TODO: Implement code to verify target");
        ////}

        /// <summary>
        /// Higher level test of the dispatching event filter.
        /// </summary>
        [TestMethod()]
        public void HighLevelTest()
        {
            TestData testData = new TestData();
            using (var syncContext = new SingleThreadSynchronizationContext())
            {
                syncContext.Send(() => this.HighLevelTestRunner(testData));
                testData.WaitHandle.WaitOne();
            }

            Assert.AreNotEqual(0, testData.SyncContextThreadId);
            Assert.AreNotEqual(0, testData.SetterThreadId);
            Assert.AreNotEqual(0, testData.EventThreadId);

            Assert.AreEqual(testData.SyncContextThreadId, testData.EventThreadId);
            Assert.AreNotEqual(testData.SyncContextThreadId, testData.SetterThreadId);
        }

        public void HighLevelTestRunner(TestData testData)
        {
            HighLevelTester tester = new HighLevelTester();
            testData.SyncContextThreadId = Thread.CurrentThread.ManagedThreadId;

            tester.DataProperty.ValueChanged +=
                (s, e) =>
                {
                    testData.EventThreadId = Thread.CurrentThread.ManagedThreadId;
                    testData.WaitHandle.Set();
                };

            ThreadPool.QueueUserWorkItem(
                o =>
                {
                    testData.SetterThreadId = Thread.CurrentThread.ManagedThreadId;
                    tester.Data = 1;
                });
        }

        public class TestData
        {
            private readonly AutoResetEvent waitHandle = new AutoResetEvent(false);

            public int SyncContextThreadId { get; set; }
            public int SetterThreadId { get; set; }
            public int EventThreadId { get; set; }

            public AutoResetEvent WaitHandle
            {
                get { return this.waitHandle; }
            }
        }

        public class HighLevelTester : MetaPropertyHost
        {
            private readonly Observable<int> observableData = new Observable<int>();

            public int Data
            {
                get { return this.observableData.Value; }
                set { this.observableData.Value = value; }
            }

            [SetEventFilter(typeof(DispatchingEventFilter))]
            public IMetaProperty<int> DataProperty
            {
                get { return this.observableData.MetaProperty; }
            }
        }
    }
}
